import Vue from 'vue'
import Vuex from 'vuex'
import {
	asyncRouterMap,
	constantRouterMap
} from "@/router"
Vue.use(Vuex)
export default new Vuex.Store({
	modules: {},
	state: {
		cachedViews: [],
		routers: constantRouterMap,
		addRouters: [],
		menulist: [],
		role: 1, // 0:后台管理员 1:维修人员
		hasGetMenu: false
	},
	mutations: {
		ADD_CACHED_VIEW: (state, view) => {
			if (state.cachedViews.includes(view.name)) return
			if (view.meta.keepAlive) {
				state.cachedViews.push(view.name)
			}
		},
		DEL_CACHED_VIEW: (state, view) => {
			const index = state.cachedViews.indexOf(view.name)
			index > -1 && state.cachedViews.splice(index, 1)
		},
		SET_ROUTERS: (state, routers) => {
			state.addRouters = routers;
			state.routers = constantRouterMap.concat(routers)
		},
		SET_menuState: (state, menustate) => {
			state.hasGetMenu = menustate;
		}
	},
	actions: {
		delCachedView({
			commit,
			state
		}, view) {
			return new Promise(resolve => {
				commit('DEL_CACHED_VIEW', view)
				resolve([...state.cachedViews])
			})
		},
		GenerateRoutes({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				let token = localStorage.getItem('token');
				if (!token) {
					resolve()
					return false
				}
				let childRouter = [];
				let mainMenu = asyncRouterMap.map(item => item);
				commit('SET_ROUTERS', [...mainMenu, {
					path: '*',
					redirect: '/404',
					hidden: true
				}])
				commit('SET_menuState', true)
				resolve()
			})
		},
		Logout({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				let loginInfo = localStorage.getItem('loginInfo');
				localStorage.clear();
				if (loginInfo) {
					localStorage.setItem('loginInfo', loginInfo);
				}
				commit('SET_menuState', false)
				resolve()
			})
		}
	}
})
